package com.zy.service.bs.impl;

import java.math.BigDecimal;
import java.util.List;

import com.zy.dao.bs.BalanceDao;
import com.zy.dao.bs.CartDao;
import com.zy.dao.bs.GoodsDao;
import com.zy.entity.bs.Balance;
import com.zy.entity.bs.Cart;
import com.zy.entity.enums.StatusEnum;
import com.zy.pojo.vos.bs.CartVo;
import com.zy.service.base.impl.BaseServiceImpl;
import com.zy.service.bs.CartService;
import com.zy.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service("cartService")
public class CartServiceImpl extends BaseServiceImpl<Cart> implements CartService {

	@Autowired
	private CartDao cartDao;
	@Autowired
	private GoodsDao goodsDao;
    @Autowired
	BalanceDao balanceDao;


	@Override
	public List<Cart> listCart(long customerId) {
		return this.cartDao.listCart(customerId);
	}

	@Override
	public void saveCart(Cart cart) {
		long time = DateUtil.getTime();
		cart.setCreateTime(time);
		cart.setModifyTime(time);
		cart.setStatus(StatusEnum.NORMAL.getValue());
		this.cartDao.save(cart);
	}

	@Override
	public void updateCart(Cart cart) {
		cart.setModifyTime(DateUtil.getTime());
		this.cartDao.updateByPrimaryKeySelective(cart);
	}

	@Override
	public void removeCart(long id) {
		try {
			this.cartDao.removeByPrimaryKey(id);
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			Cart cart = new Cart();
			cart.setId(id);
			cart.setModifyTime(DateUtil.getTime());
			cart.setStatus(StatusEnum.DELETE.getValue());
			this.cartDao.updateByPrimaryKeySelective(cart);
		}
	}

	@Override
	public void recover(long id) {
		Cart cart = new Cart();
		cart.setId(id);
		cart.setModifyTime(DateUtil.getTime());
		cart.setStatus(StatusEnum.NORMAL.getValue());
		this.cartDao.updateByPrimaryKeySelective(cart);
	}

	@Override
	public CartVo calc(List<Long> goodsIds, long customerId) {
		BigDecimal total = BigDecimal.valueOf(0);
		for (Long id : goodsIds) {
			total = total.add(this.goodsDao.getByPrimaryKey(id).getPrice());
		}
		Balance search = new Balance();
		search.setCustomerId(customerId);
		CartVo carVo = new CartVo();
		carVo.setTotalPrice(total);
		carVo.setTotalPoint(this.balanceDao.get(search).getBalance());
		return carVo;
	}
}
